<?php

namespace app\office\model;

use think\Model;

class Organization extends Model
{
    //增加记录时,自动完成状态设置;
    protected $insert=[
      'static'  =>  1,
    ];
    
    //在模块内再次确保开启自动时间戳;
    protected $autoWriteTimestamp='datetime';
  
    //设置自动时间戳格式为datetime格式;
    protected $type=[
      'create_time'=>'datetime',
      'update_time'=>'datetime',
    ];
    
    // 设置密码
    protected function setPasswordAttr($value){
      $salt='salt';
      return md5($value.$salt).$salt;
    }
    
    // 设置读取器create_time
    protected function getCreateTimeAttr($create_time){
      return date('Y-m-d',strtotime($create_time));     /* 注意:此处用到了strtotime函数 */
    }
    
    // 设置读取器update_time
    protected function getUpdateTimeAttr($update_time){
      return date('Y-m-d',strtotime($update_time));     /* 注意:此处用到了strtotime函数 */
    }
    
    // 设置读取器父节点返回值parent_id_text
    protected function getParentIdTextAttr($value,$data){
      $parentlist=$this::column('title','id');
      if(0==$data['parent_id']){
        return '无';
      }
      return $parentlist[$data['parent_id']]; 
    }
    
    // 设置读取器is_sth
    protected function getIsSthAttr($value){
      $static=[0=>'否',1=>'是'];
      return $static[$value];
    }
    
    // 设置读取器sth_num
    protected function getSthNumAttr($value){
      return $value." ??";
    }
    
    // 设置读取器delat_time,不存在的属性
    protected function getDeltaTimeAttr($value,$data){
      $delta_time=floor((strtotime($data['update_time'])-strtotime($data['create_time']))/3600/24);       /* 此处根据情况可选择round,ceil,floor */
      return $delta_time." 天";
    }
    
    // 设置读取器static
    protected function getStaticAttr($value){
      $static=[
      0=>'已离职',
      1=>'正常',
      2=>'借调',
      3=>'休假',
      4=>'其他',
      ];
      return $static[$value];
    }
    
    // 设置查询范围
    protected function scopeStatic($query){
      $query->where('static','>',0);
    }
    
    // 获取无限分类结构数组organization_tree
    public static function getTree($parent_id=0,$level=0){
      $tree=array();
      foreach(self::select() as $key=>$row){
        if($row['parent_id']==$parent_id){
          $row['level']=$level;
          $tree[]=$row;
          $tree=array_merge($tree,self::getTree($row['id'],$level+1));
        }
      }
      return $tree;
    }
    
      /**
      * 多对多关系资源
      *
      * @param  
      * @return 
      */
      public function employee(){
        return $this->belongsToMany('Employee','employee_organization');
      }

      /**
      * 多对多关系资源
      *
      * @param  
      * @return 
      */
      public function position(){
        return $this->belongsToMany('Position','organization_position');
      }
}
